import { defineStore } from 'pinia'
import { ref, toRaw } from 'vue'
import type { HistoryLogs } from '@/types/loginType'
export const useHistoryStore = defineStore('useHistoryStore', () => {
  const historyLogsData = ref<HistoryLogs[]>([])
  //  操作方法
  const history = localStorage.getItem('history')

  historyLogsData.value =
    history !== null
      ? JSON.parse(history)
      : [{ time: new Date().toLocaleDateString(), items: 0, data: [] }]

  // 添加一个记录
  function addHistory(id: string) {
    // 初始化
    const time = new Date().toLocaleDateString()
    //
    if (time !== historyLogsData.value[0].time) {
      historyLogsData.value.unshift({ time, items: 0, data: [] })
    } else {
      const index = historyLogsData.value[0].data.indexOf(id)
      if (index !== -1) {
        // 二次访问
        historyLogsData.value[0].data.splice(index, 1)
        historyLogsData.value[0].data.unshift(id)
      } else {
        // 第一次访问
        historyLogsData.value[0].data.unshift(id)
        historyLogsData.value[0].items++
      }
    }

    if (historyLogsData.value.length > 15) {
      historyLogsData.value.pop()
    }
    setHistoryLocal()
  }

  function setHistoryLocal() {
    localStorage.setItem('history', JSON.stringify(historyLogsData.value))
  }

  return { historyLogsData, addHistory }
})
